/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunji.framework_template.common.log.LoggerWrapper;
import com.yunji.framework_template.common.redis.RedisHelper;

/**
 * ClassName:RedisLoadTest <br/>
 * Date: 2017年10月13日 上午9:33:45 <br/>
 * 
 * @author fenglibin
 * @version
 * @see
 */
@Controller
@Component("redisLoadTestControler")
public class RedisLoadTestControler {

    private static final LoggerWrapper logger = LoggerWrapper.getLogger(RedisLoadTestControler.class);

    @Autowired
    private RedisHelper                redisHelper;

    @ResponseBody
    @RequestMapping(value = "/redisLoadTest", method = { RequestMethod.POST, RequestMethod.GET })
    public String loadTest(HttpServletRequest request, HttpServletResponse response) {
        int times = Integer.parseInt(request.getParameter("times"));
        int threads = Integer.parseInt(request.getParameter("threads"));
        doLoadTest(times, threads);
        return "OK";
    }

    public void doLoadTest(final int times, int threads) {
        int total = times * threads * 2;
        logger.info("Begin to do " + total + " times redis write load test in " + threads + " threads, now is:"
                    + new Date());
        for (int i = 0; i < threads; i++) {
            final int currentThread = i;
            new Thread() {

                public void run() {
                    logger.info("Begin to start thread " + currentThread + ", now is：" + new Date());
                    for (int time = 0; time < times; time++) {
                        int random = (int) (Math.random() * 100000);
                        String key = System.currentTimeMillis() + "" + random;
                        logger.debug("Current operate key is:" + key);
                        redisHelper.set(key, key);
                        redisHelper.delete(key);
                    }
                    logger.info("Thread " + currentThread + " end, now is:" + new Date());
                }
            }.start();
        }
    }
}
